package org.tarena.dang.service;

import java.sql.SQLException;

import org.tarena.dang.dao.UserDAO;
import org.tarena.dang.dao.impl.UserDAOImpl;
import org.tarena.dang.entity.User;
import org.tarena.dang.util.Constant;
import org.tarena.dang.util.EmailUtils;
import org.tarena.dang.util.EncryptUtil;
import org.tarena.dang.util.MD5Utils;
import org.tarena.dang.util.VerifyCodeUtils;

public class UserServiceImp implements UserService {
	
	@Override
	public String register(User user, String ip) throws Exception {
		UserDAO userDAO = new UserDAOImpl();
		//将密码加密
		String md5Pwd = 
			MD5Utils.md5(user.getPassword());
		user.setPassword(md5Pwd);
		//设置系统用户等级为初级
		user.setUserIntegral(
				Constant.NORMAL_LEVEL);
		//设置邮箱未通过验证
		user.setEmailVerify(false);
		//设置最后登录时间
		user.setLastLoginTime(System.currentTimeMillis());
		//设置最后登录IP
		user.setLastLoginIp(ip);
		userDAO.save(user);
		//生成邮箱验证码
		String code = VerifyCodeUtils.getVerifyCode(user.getId());
		//this.code = code;
		System.out.println("send code:"+code);
		//将用户id和uuid发送给用户邮箱
		EmailUtils.sendEmail( user.getEmail(),code);
		//设置user对象的email_verify_code字段
		String uuid = VerifyCodeUtils.getUUID(code);
		user.setEmailVerifyCode(uuid);
		userDAO.update(user);
		System.out.println("注册成功！");
		return code;
	}

	@Override
	public User login(User user) throws SQLException {
		UserDAO userDAO = new UserDAOImpl();
		User u = new User();
		u = userDAO.findByPwd(user.getEmail(),EncryptUtil.md5Encrypt(user.getPassword()));
		System.out.println("email cod=="+u.getEmailVerifyCode());
		return u;
	}

	@Override
	public void update(User user) throws SQLException {
		UserDAO userDAO = new UserDAOImpl();
		userDAO.update(user);
		
	}

	@Override
	public User checkEmailCode(User user) {
		UserDAO userDAO = new UserDAOImpl();
		try {
			user = userDAO.findById(user.getId());
			return user;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void updateEmailVerify(int id) {
		UserDAO userDAO = new UserDAOImpl();
		try {
			userDAO.updateEmailVerify(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean findByEmail(String email) throws SQLException {
		UserDAO dao = new UserDAOImpl();
			if(!dao.findByEmail(email)){
				System.out.println("邮箱可以使用！");
				return true;
			}
		return false;
	}


	
}
